from lxml import etree
import requests
import re
from result import *
import index
from fontTools.ttLib import TTFont
from io import BytesIO


def get_chapter(link, p_chapter_name, platform):
    """
    获取书相关的属性 包含  书ID、书名、章节ID、章节名称
    """
    try:
        data = requests.get(link)  # 解析html
        r = data.content
        html_doc = str(r, 'utf-8')   # 此举旨在正确编码，避免乱码
        html = etree.HTML(html_doc)

        book_info = html.xpath("//div[@class='info fl']")[0]  # 书信息
        book_id = book_info.xpath(".//a[1]/@data-bid")[0]  # 书ID
        book_name = book_info.xpath(".//a[1]/text()")[0]  # 书名
        auth_id = book_info.xpath(".//a[1]/@data-auid")[0]  # 作者ID
        if auth_id != "0":
            auth_name = book_info.xpath(".//a[2]/text()")[0]  # 作者名称
        else:
            auth_name = book_info.xpath(".//i[1]/text()")[0]  # 作者名称
        chapter_id = html.xpath("//div[@class='text-wrap']/@data-cid")[0]  # 章节ID
        chapter_name = html.xpath("//div[@class='text-head']//h3/text()")[0]  # 章节名
        last_update_time = book_info.xpath(".//span[@class='j_updateTime']/text()")[0]  # 更新日期
        if last_update_time is not None:
            last_update_time += ":00"
        else:
            last_update_time = "2019-03-03 03:03:03"
        content_list = []  # 章节内容
        for item in html.xpath("//div[@class='read-content j_readContent']/p"):
            text = item.text.strip()  # 移除内容开头和结尾（默认为空格或换行符）或字符序列
            if re.match("注.+?推荐|注.+?收藏|^……$", text) is None:  # 忽略小说内容里有 一些拉票的描述
                content_list.append(text)

        if p_chapter_name != chapter_name.strip():   # 判断传入的章节名称和抓取的章节名称是否一致
            print("章节名称不一致", "传：", p_chapter_name, "抓：", chapter_name)
        # 将章节内容 写入数据库
        index.insertData(book_id, book_name.strip(), chapter_id, p_chapter_name, content_list, last_update_time, auth_id, platform, link)
        # 将作者ID和作者名 写入数据库 如果作者ID为0 则不插入
        if auth_id != "0":
            index.insert_auth_data(auth_id, auth_name.strip(), platform)
        return success(content_list)
    except Exception as ex:
        print(p_chapter_name, "小说内容异常", ex)
        return error(1, "数据异常")


def get_font(url):
    response = requests.get(url)
    font = TTFont(BytesIO(response.content))
    cmap = font.getBestCmap()
    font.close()
    return cmap


def get_encode(cmap, values):
    WORD_MAP = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7',
                'eight': '8', 'nine': '9', 'period': '.'}
    word_count = ''
    list = values.split(';')
    list.pop(-1)
    for value in list:
        # value = value[2:]
        key = cmap[int(value)]
        word_count += WORD_MAP[key]
    return word_count


def convert_num(link,content):
    try:
        num_list = []
        cmap = get_font(link)
        num_list.append(get_encode(cmap, content))
        print("result-->", num_list)
    except Exception as e:
        print(e)
        return error(1, "系统繁忙")
    return success(','.join(num_list))


if __name__ == "__main__":
    print(get_chapter("https://read.qidian.com/chapter/5mUQzywwHah51l-ULjeaVw2/tbxSWTDuvxdp4rPq4Fd4KQ2", "第6章：这不符合套路", "qidian"))
    # get_chapter("https://read.qidian.com/chapter/5mUQzywwHah51l-ULjeaVw2/ZbEnd2ZcqXKaGfXRMrUjdw2", "qidian")
    print(convert_num("https://qidian.gtimg.com/qd_anti_spider/OWCyQWVJ.woff",
                      "&#100158;&#100155;&#100160;&#100159;&#100152;&#100160;"))

